const cacheUserKey = 'cache::user::info';
const cacheTokenKey = 'access_token';
const customRequst = require('/customRequst.js');

//获取用户信息
function getUserInfo(){

  let userInfo = wx.getStorageSync(cacheUserKey);
  if(userInfo != undefined &&userInfo != null && userInfo != ''){
    //判断是否数据已经过期
    let timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    let expiretime = userInfo.expiretime;
    if(timestamp > expiretime){
      userInfo = [];
      clearUserInfo();
    }
  }
  return userInfo;
}

//获取用户token
function getUserToken(){
  let token = wx.getStorageSync(cacheTokenKey);
  if(token == undefined || token == null || token == ''){
    token = '';
  }
  return token;
}

//添加用户信息到本地缓存中
function setUserInfo(objData){
  
  try{
    wx.setStorageSync(cacheUserKey, objData)
    wx.setStorageSync(cacheTokenKey,objData.token);
    return true;
  }catch(e){
    console.log(e);
    return false;
  }
}

//修改用户数据
function updateUserInfo(data){
  let oldUserInfo = this.getUserInfo();
  for(let i in data){
    oldUserInfo[data[i]['key']] = data[i]['value'];
  }
  this.setUserInfo(oldUserInfo);
}

//清除缓存数据
function clearUserInfo(){
  wx.removeStorageSync(cacheUserKey);
  wx.removeStorageSync(cacheTokenKey);
}

//用户登录
function userLogin(code,account,psd,extentedData){
  let url = '';
  let postData = {};
  if(code != null && code != ''){
    //调用微信登陆接口
    url ='api/userlogin/wechat';
    postData = {code:code};
  }else{
    //调用账号密码登录接口
    url ='api/userlogin/wechat';
    postData = {account:account,password:psd};
  }
  if(extentedData != undefined && extentedData != null && extentedData != ''){
    postData  = Object.assign(postData,extentedData);
  }
  return new Promise(function(successFun,errorFun){
    customRequst.postRequest(url,postData).then(function(re){
      
      if(re.code == 1){
        setUserInfo(re.data);
        successFun(re.data);
      }else if(re.code ==2){
        wx.showModal({
          title:'登录提示',
          content:'您还未绑定手机号，请先绑定手机号！',
          success:function(res){
            if (res.confirm) {
              wx.navigateTo({
                url:'/pages/users/bindmobile/index?openid=' + re.data.openid
              })
            }
          }
        });
      }else if(re.code == 3){
        wx.showModal({
          title:'登录提示',
          content:'您还未绑定微信，请先绑定微信！',
          success:function(res){
            if (res.confirm) {
              wx.navigateTo({
                url:'/pages/users/bindwechat/index'
              })
            }
          }
        });
      } else{
        //提示错误消息
        wx.showToast({
          title: re.msg,
          icon : 'error',
          duration :'2000',
        })
        errorFun({code:re.code,msg:re.msg});
      }
    })
  })
}
//外部调用接口
module.exports.getUserInfo = getUserInfo;
module.exports.userLogin = userLogin;
module.exports.getUserToken = getUserToken;
module.exports.setUserInfo = setUserInfo;
module.exports.clearUserInfo = clearUserInfo;
module.exports.updateUserInfo = updateUserInfo;
